# -*- coding: utf-8 -*-
# !/usr/bin/env python
# @Time    : 2017/11/27 16:16
# @Author  : xincheng.zhao
# @File    : interface.py
# @Software: PyCharm
import hashlib
import json
import time

import os

import datetime
from django.core.paginator import Paginator

from bsfault.models import event, info, log
from random import Random

'''
查询分页  deploy_list = modelname.objects.all().values() 
默认是每页5行的内容，与前端默认行数一致
取出该表所有数据，每页显示10条数据
必须带有rows和total这2个key，total表示总页数，rows表示每行的内容
'''


def page(deploy_list, limit, offset):
    if not offset:
        offset = 0
    if not limit:
        limit = 5
    return {"data": Paginator(list(deploy_list), limit).page(int(int(offset) / int(limit) + 1)),
            "response_data": {'total': deploy_list.count(), 'rows': []}}


'''
 专门处理时间序列化
'''


class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, datetime.date):
            return obj.strftime("%Y-%m-%d")
        else:
            return json.JSONEncoder.default(self, obj)


# MD5
def md5(str):
    m2 = hashlib.md5()
    m2.update(str)
    return m2.hexdigest()


'''
生成特征码
'''


def signature(randomlength=5):
    str = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        str += chars[random.randint(0, length)]
    return str


'''
处理父级
'''


def parentId(pid):
    if not pid:
        return None;
    else:
        return pid


def fault_info():
    event = info.objects.all().values('fault_time', 'fault_events')
    path = os.path.abspath('.') + '/log/'
    t = time.strftime("%Y-%m-%d", time.localtime())
    fp = path + 'fault_' + t + ".txt"
    if not os.path.exists(path):
        os.mkdir(path)
    if not os.path.exists(fp):
        os.mknod(fp)
    file = open(fp, 'a', )
    for ev in event:
        file.write('在' + ev['fault_time'].strftime('%Y-%m-%d %H:%M:%S') + ': ' + ev['fault_events'] + '\n')
    file.close()
    info.objects.filter().delete()


def operator_info():
    event = log.objects.all().values('fault_time', 'log')
    path = os.path.abspath('.') + '/log/'
    t = time.strftime("%Y-%m-%d", time.localtime())
    fp = path + 'oper_' + t + ".txt"
    if not os.path.exists(path):
        os.mkdir(path)
    if not os.path.exists(fp):
        os.mknod(fp)
    file = open(fp, 'a', )
    for ev in event:
        file.write('在' + ev['fault_time'].strftime('%Y-%m-%d %H:%M:%S') + ': ' + ev['log'] + '\n')
    file.close()
    log.objects.filter().delete()


'''
处理推理
'''


def reason_x(id):  # 已经发生事件
    events = ''
    path = event.objects.filter(id=str(id)).values('path')[0]['path']
    for i in path.split('/'):
        if i == '' or i == '0':
            continue
        events = events + event.objects.filter(id=str(i)).values('events')[0]['events'] + ';'
    return events + 'x;'


def reason_m(id):  # 发生原因
    events = ''
    events = events + reason_x(id)
    path = event.objects.filter(id=id).values('path')[0]['path']
    list = event.objects.filter(path__contains=0).values('events')
    for ev in list:
        events = events + ev['events'] + ";"
    return events
